package com.rf.richfitwheel.admin.sys.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rf.richfitwheel.admin.sys.dao.DictionaryMapper;
import com.rf.richfitwheel.admin.sys.dao.SqlAdapterMapper;
import com.rf.richfitwheel.admin.sys.model.Dictionary;
import com.rf.richfitwheel.admin.sys.model.DictionaryExample;
import com.rf.richfitwheel.admin.sys.service.SysDicService;
import com.rf.richfitwheel.common.contants.Constant;
import com.rf.richfitwheel.common.exception.BusinessException;
import com.rf.richfitwheel.common.utils.PageUtils;
import com.rf.richfitwheel.common.utils.StringUtils;
import com.rf.richfitwheel.common.utils.TreeUtils;
import com.rf.richfitwheel.common.utils.UuidUtil;

import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service("sysDicService")
public class SysDicServiceImpl implements SysDicService {
    @Autowired
    private DictionaryMapper dictionaryMapper;

    @Autowired
    private SqlAdapterMapper sqlAdapterMapper;//注入dao

    /**
     * 分页数据
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        PageUtils pageUtils = PageUtils.getPageInfo(params);
        Page<Dictionary> p = PageHelper.startPage(pageUtils.getPage(), pageUtils.getLimit());
        Dictionary dictionary = (Dictionary) JSONObject.toBean(JSONObject.fromObject(params.get("dataForm")), Dictionary.class);
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(dictionary.getClassCode())) {
            criteria.andClassCodeLike("%" + dictionary.getClassCode() + "%");
        }
        if (StringUtils.isNotBlank(dictionary.getClassName())) {
            criteria.andClassNameLike("%" + dictionary.getClassName() + "%");
        }
		/*StringBuffer sql=new StringBuffer(" select * from sys_dictionary");
		if(dictionary!=null){
			sql.append(" where 1=1");
			if(StringUtils.isNotBlank(dictionary.getClassCode()))
				sql.append(" and class_code like '%").append(dictionary.getClassCode()+"%'");
			if(StringUtils.isNotBlank(dictionary.getClassName()))
				sql.append(" and class_name like '%").append(dictionary.getClassName()+"%'");
		}
		sql.append(" order by class_code,data_code ");
		sqlAdapterMapper.selectSQL(sql.toString());*/
        example.setOrderByClause(" class_code,data_order ");
        List<Dictionary> list = dictionaryMapper.selectByExample(example);
        pageUtils = new PageUtils(p);
        return pageUtils;
    }

    @Override
//	@Caching(evict={@CacheEvict(value="dics",key="'dicAll'"),@CacheEvict(value="dics",key="#dictionary.id + '_selectById'"),@CacheEvict(value="dics",key="#dictionary.classCode + '_queryByClassCode'"),@CacheEvict(value="dics",key="#dictionary.classCode + '_queryByClassCodeStatusNormal'")})
    public void save(Dictionary dictionary) throws Exception {
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        criteria.andClassCodeEqualTo(dictionary.getClassCode());
        criteria.andDataCodeEqualTo(dictionary.getDataCode());
        List<Dictionary> dictionaries = dictionaryMapper.selectByExample(example);
        if(!dictionaries.isEmpty()){
            throw new BusinessException("类型编码+键值不允许重复");
        }
        dictionary.setId(UuidUtil.get32UUID());
        if (StringUtils.isBlank(dictionary.getParentId())) {
            dictionary.setParentId("0");
        }
        dictionaryMapper.insert(dictionary);
    }

    @Override
//	@Caching(evict={@CacheEvict(value="dics",key="'dicAll'"),@CacheEvict(value="dics",key="#dictionary.id + '_selectById'"),@CacheEvict(value="dics",key="#dictionary.classCode + '_queryByClassCode'"),@CacheEvict(value="dics",key="#dictionary.classCode + '_queryByClassCodeStatusNormal'")})
    public void update(Dictionary dictionary) throws Exception {
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        criteria.andClassCodeEqualTo(dictionary.getClassCode());
        criteria.andDataCodeEqualTo(dictionary.getDataCode());
        criteria.andIdNotEqualTo(dictionary.getId());
        List<Dictionary> dictionaries = dictionaryMapper.selectByExample(example);
        if(!dictionaries.isEmpty()){
            throw new BusinessException("类型编码+键值不允许重复");
        }
        if (StringUtils.isBlank(dictionary.getParentId())) {
            dictionary.setParentId("0");
        }
        dictionaryMapper.updateByPrimaryKeySelective(dictionary);
    }

    @Override
    public void updateValueByKey(String key, String value) {
    }

    @Override
//	@CacheEvict(value="dics",allEntries=true)
    public void deleteBatch(String[] ids) {
        for (String id : ids) {
            dictionaryMapper.deleteByPrimaryKey(id);
        }
    }

    @Override
    public String getValue(String key) {
        return key;
    }

    /**
     * 主键获取字典
     *
     * @param id
     * @return
     * @throws Exception
     */
//	@Cacheable(value="dics",key="#id + '_selectById'")
    public Dictionary selectById(String id) throws Exception {
        Dictionary dictionary = dictionaryMapper.selectByPrimaryKey(id);
        if (StringUtils.isNotBlank(dictionary.getParentId())) {
            Dictionary parent = dictionaryMapper.selectByPrimaryKey(dictionary.getParentId());
            if (parent != null) {
                dictionary.setParentName(parent.getClassName() + "/" + parent.getDataName());
            }
        }
        return dictionary;
    }

    @Override
    public <T> T getConfigObject(String key, Class<T> clazz) {
        return null;

    }

    @Override
//	@Cacheable(value="dics",key="#classCode + '_queryByClassCode'")
    public List<Dictionary> queryByClassCode(String classCode) {
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        criteria.andClassCodeEqualTo(classCode);
        criteria.andStateEqualTo(Constant.COMMON_STATUS_NORMAL);
        example.setOrderByClause(" data_order ");
        return dictionaryMapper.selectByExample(example);
    }

    @Override
//	@Cacheable(value="dics",key="'dicAll'")
    public List<Dictionary> queryAll() {
        DictionaryExample example = new DictionaryExample();
        example.setOrderByClause(" class_code ");
        return dictionaryMapper.selectByExample(example);
    }

    /* （非 Javadoc）
     * <p>Title: getDicTreeByClassCode</p>
     * <p>Description: </p>
     * @param classCode
     * @return
     * @see com.rf.cloud.annuity.sys.service.SysDicService#getDicTreeByClassCode(java.lang.String)
     */
    @Override
    public List<TreeUtils> getDicTreeByClassCode(String classCode) throws Exception {
        String[] codes = classCode.split(",");
        List<Dictionary> list = new ArrayList<Dictionary>();
        for (String code : codes) {
            list.addAll(queryByClassCode(code));
        }
        List<TreeUtils> treeList = TreeUtils.getTreeList(list, "id", "parentId", "dataName", null, "dataCode");
        return treeList;
    }

    /* （非 Javadoc）
     * queryByClassCodeStatusNormal
     * @param classCode
     * @return
     * @see com.rf.cloud.annuity.sys.service.SysDicService#queryByClassCodeStatusNormal(java.lang.String)
     */
    @Override
//	@Cacheable(value="dics",key="#classCode + '_queryByClassCodeStatusNormal'")
    public List<Dictionary> queryByClassCodeStatusNormal(String classCode) {
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        criteria.andClassCodeEqualTo(classCode);
        criteria.andStateEqualTo(Constant.COMMON_STATUS_NORMAL);
        example.setOrderByClause(" data_order ");
        return dictionaryMapper.selectByExample(example);
    }

    @Override
    public Dictionary queryByClassCodeAndDataCode(String classCode, String dataCode) {
        DictionaryExample example = new DictionaryExample();
        DictionaryExample.Criteria criteria = example.createCriteria();
        criteria.andClassCodeEqualTo(classCode);
        criteria.andDataCodeEqualTo(dataCode);
        example.setOrderByClause(" data_order ");
        List<Dictionary> dictionaries = dictionaryMapper.selectByExample(example);
        if (dictionaries.size() > 0) {
            return dictionaries.get(0);
        } else {
            return new Dictionary();
        }
    }
}
